<template>
  <el-select class="select-tree" ref="select" :size="size" :value="value" :disabled="disabled" v-model="valueName"
             :multiple="multiple" :collapse-tags="collapseTags"
             :clearable="clearable" @remove-tag="removeTag" :placeholder="placeholder"
             @clear="clearHandle" style="width: 100%">
    <el-option :value="valueName" class="options">
      <el-tree id="tree-option"
               v-if="clear"
               ref="selectTree"
               :check-strictly="true"
               :default-expand-all="true"
               :expand-on-click-node="false"
               :check-on-click-node="multiple"
               :accordion="accordion"
               :data="options"
               :props="props"
               :node-key="props.value"
               :show-checkbox="multiple"
               @check="handleCheckChange"
               @node-click="handleNodeClick">
                <span slot-scope="{ data }" style="font-weight: normal">
                    <i :class="[data.color!=null?'ification_col':'']" :style="{'background-color':data.color}"></i>
                    &nbsp;&nbsp;
                    {{ data[props.label] }}
                </span>
      </el-tree>
    </el-option>
  </el-select>
</template>
<script>
export default {
  name: "el-select-tree",
  props: {
    // 配置项
    props: {
      type: Object,
      default: () => {
        return {
          value: 'name',
          children: 'children',
          label: 'nameCn'
        }
      }
    },
    // 选项列表数据(树形结构的对象数组)
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 初始值（单选）
    value: {
      type: [String, Array, Number],
      default: () => {
        return ""
      }
    },
    // 可清空选项
    clearable: {
      type: Boolean,
      default: true
    },
    // 自动收起
    accordion: {
      type: Boolean,
      default: false
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    collapseTags: {
      type: Boolean,
      default: () => false
    },
    size: {
      type: String,
      default: () => "small"
    },
    placeholder: {
      type: String,
      default: () => "请选择"
    },
  },
  data() {
    return {
      // valueName: '', // 输入框显示值
      clear: true,
    }
  },
  computed: {
    valueName() {
      let valueName = this.multiple ? [] : "";
      let selection = this.multiple ? [] : "";
      let loop = (data) => {
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (this.multiple) {
              if (this.value && this.value.includes(item[this.props.value])) {
                valueName.push(item[this.props.label])
                selection.push(item);
              }
            } else {
              if (this.value && this.value === item[this.props.value]) {
                valueName = item[this.props.label];
                selection = item;
              }
            }

            if (item.children && item.children.length > 0) {
              loop(item.children);
            }
          }
        }
      }
      if (this.value && this.value.length > 0) {
        loop(this.options);
      }

      if (selection && selection.length > 0) {
        if (!this.multiple) {
          this.$refs["selectTree"].setCheckedNodes(selection)
        } else {
          for (let i = 0; i < selection.length; i++) {
            this.$nextTick(()=>{
              this.$refs["selectTree"] && this.$refs["selectTree"].setChecked(selection[i][this.props.value], true)
            })
          }
        }
      }
      return valueName;
    }
  },
  mounted() {
    this.initHandle();
  },
  methods: {
    removeTag() {
      let v = this.valueName;
      let selection = [];
      let unSelection = [];
      let loop = (data) => {
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (v && v.indexOf(item[this.props.value]) !== -1) {
              selection.push(item[this.props.value]);

              if (item.children && item.children.length > 0) {
                loop(item.children);
              }

            } else {
              unSelection.push(item[this.props.value]);
              if (item.children && item.children.length > 0) {
                loop(item.children);
              }
            }
          }
        }
      }
      loop(this.options);

      this.clearTreeCheck(unSelection, 'only');
    },
    // 初始化显示
    initHandle() {
      this.initScroll()
    },
    // 初始化滚动条
    initScroll() {
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
        let scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
        scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
        scrollBar.forEach(ele => ele.style.width = 0)

        let dropdown__list = document.querySelectorAll(".options");
        for (let i = 0; i < dropdown__list.length; i++) {
          let item = dropdown__list[i];
          let scrollbar__wrap = item.parentNode;
          Object.assign(item.parentNode.style, {padding: 0})
          Object.assign(scrollbar__wrap.parentNode.style, {margin: 0, overflow: "hidden"})
        }
      })
    },
    handleCheckChange(_, {checkedNodes}) {
      let node_name = checkedNodes.map(item => item[this.props.value]);

      this.$emit('update:value', node_name);
    },
    //  单选
    handleNodeClick(node) {
      if (!this.multiple) {
        this.$refs.select.blur();
        this.$emit('update:value', node[this.props.value]);
        this.$emit('input', node[this.props.value]);
        this.$emit('change', node[this.props.value]);
      }
    },
    // 清除选中
    clearHandle() {
      this.valueName = ''
      this.clearSelected()
      this.$emit('update:value', "");
      this.clear = false;
      this.$nextTick(() => {
        this.clear = true;
      })
    },
    // 清空选中样式
    clearSelected() {
      let allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    },
    clearTreeCheck(v, t) {
      if (t === "only") {
        for (let i = 0; i < v.length; i++) {
          let key = v[i];
          this.$refs["selectTree"].setChecked(key, false)
        }
      }
    }
  },
}
</script>
<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 300px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}

.el-select-dropdown__item.selected {
  font-weight: normal;
}

ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}

.el-tree-node__label {
  font-weight: normal;
}

.el-tree >>> .is-current .el-tree-node__label {
  color: #409EFF;
  font-weight: 700;
}

.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

.el-popper {
  z-index: 9999;
}

.ification_col {
  width: 20px;
  height: 10px;
  display: inline-block;
}
</style>
